// API 基础 URL
const API_BASE_URL = 'http://127.0.0.1:8000';

// 获取 DOM 元素
const todoList = document.getElementById('todoList');
const newTodoTitleInput = document.getElementById('newTodoTitle');
const newTodoDescriptionInput = document.getElementById('newTodoDescription');
const addTodoButton = document.getElementById('addTodoButton');
const emptyState = document.getElementById('emptyState');
const editModal = document.getElementById('editModal');
const closeButton = editModal.querySelector('.close-button');
const editTodoTitleInput = document.getElementById('editTodoTitle');
const editTodoDescriptionInput = document.getElementById('editTodoDescription');
const saveEditButton = document.getElementById('saveEditButton');

let currentEditingTodoId = null;

// --- API 调用函数  ---
async function fetchTodos() {
    try {
        const response = await fetch(`${API_BASE_URL}/todos/`);
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) {
        console.error('获取待办事项失败:', error);
        alert('获取待办事项失败，请检查后端服务是否运行。');
        return [];
    }
}
async function createTodo(title, description) {
    try {
        const response = await fetch(`${API_BASE_URL}/todos/`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ title, description }),
        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) { console.error('创建待办事项失败:', error); alert('创建待办事项失败。'); }
}
async function updateTodo(id, data) {
    try {
        const response = await fetch(`${API_BASE_URL}/todos/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return await response.json();
    } catch (error) { console.error('更新待办事项失败:', error); alert('更新待办事项失败。'); }
}
async function deleteTodo(id) {
    try {
        const response = await fetch(`${API_BASE_URL}/todos/${id}`, { method: 'DELETE' });
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        return true;
    } catch (error) { console.error('删除待办事项失败:', error); alert('删除待办事项失败。'); return false; }
}

// --- DOM 操作和事件处理 ---
function renderTodos(todos) {
    todoList.innerHTML = '';
    emptyState.style.display = todos.length === 0 ? 'flex' : 'none';

    todos.forEach(todo => {
        const todoItem = document.createElement('div');
        todoItem.className = `todo-item ${todo.completed ? 'completed' : ''}`;
        todoItem.dataset.id = todo.id;
        todoItem.dataset.title = todo.title;
        todoItem.dataset.description = todo.description || '';
        todoItem.dataset.completed = todo.completed;

        const isCompleted = todo.completed;

        todoItem.innerHTML = `
            <div class="todo-content">
                <h3>${todo.title}</h3>
                <p>${todo.description || '无描述'}</p>
            </div>
            <div class="todo-actions">
                <button class="btn secondary-btn toggle-completed-btn">
                    <span class="material-icons">${isCompleted ? 'undo' : 'done'}</span>
                    ${isCompleted ? '标记未完' : '标记完成'}
                </button>
                <button class="btn secondary-btn edit-btn">
                    <span class="material-icons">edit</span>
                    编辑
                </button>
                <button class="btn danger-btn delete-btn">
                    <span class="material-icons">delete</span>
                    删除
                </button>
            </div>
        `;
        todoList.appendChild(todoItem);
    });
}

async function loadAndRenderTodos() {
    const todos = await fetchTodos();
    renderTodos(todos);
}

addTodoButton.addEventListener('click', async () => {
    const title = newTodoTitleInput.value.trim();
    const description = newTodoDescriptionInput.value.trim();
    if (!title) return alert('待办事项标题不能为空！');
    await createTodo(title, description);
    newTodoTitleInput.value = '';
    newTodoDescriptionInput.value = '';
    loadAndRenderTodos();
});

todoList.addEventListener('click', async (event) => {
    const button = event.target.closest('button');
    if (!button) return;
    const todoItem = button.closest('.todo-item');
    const todoId = parseInt(todoItem.dataset.id);

    if (button.classList.contains('toggle-completed-btn')) {
        const completed = todoItem.dataset.completed === 'false'; // Toggle the state
        await updateTodo(todoId, { completed });
        loadAndRenderTodos();
    } else if (button.classList.contains('edit-btn')) {
        currentEditingTodoId = todoId;
        editTodoTitleInput.value = todoItem.dataset.title;
        editTodoDescriptionInput.value = todoItem.dataset.description;
        editModal.style.display = 'block';
    } else if (button.classList.contains('delete-btn')) {
        if (confirm('确定要删除这个待办事项吗？')) {
            await deleteTodo(todoId);
            loadAndRenderTodos();
        }
    }
});

saveEditButton.addEventListener('click', async () => {
    const title = editTodoTitleInput.value.trim();
    const description = editTodoDescriptionInput.value.trim();
    if (!title) return alert('标题不能为空！');
    if (currentEditingTodoId !== null) {
        await updateTodo(currentEditingTodoId, { title, description });
        editModal.style.display = 'none';
        loadAndRenderTodos();
    }
});

function closeModal() {
    editModal.style.display = 'none';
    currentEditingTodoId = null;
}
closeButton.addEventListener('click', closeModal);
window.addEventListener('click', (event) => {
    if (event.target === editModal) closeModal();
});

document.addEventListener('DOMContentLoaded', loadAndRenderTodos);